import { BadRequestException, Injectable } from '@nestjs/common';
import { WxService } from '../wx/wx.service';
import { IWxPhoneInfo, IWxSessionResult } from '../wx/types/wx.type';
import { UserService } from '~/modules/user/user.service';
import { TokenService } from '~/modules/auth/services/token.service';
import { UserEntity } from '~/modules/user/user.entity';
import { ErrorEnum } from '~/constants/error-code.constant';

@Injectable()
export class MpAuthService {
  constructor(
    private wxService: WxService,
    private userService: UserService,
    private tokenService: TokenService
  ) {}

  async login(code: string, tenantId: number): Promise<string> {
    if (!code) {
      throw new BadRequestException(ErrorEnum.INVALID_CODE);
    }

    const result: IWxSessionResult = await this.wxService.getSession(code);

    const user: UserEntity = await this.userService.registerByOpenid(result.openid, tenantId);

    const token = await this.tokenService.generateAccessToken(user.id, []);

    return token.accessToken;
  }

  async getPhone(code: string, uid: number): Promise<string> {
    const mobileInfo: IWxPhoneInfo = await this.wxService.validatePhoneByCode(code);

    if (!mobileInfo) {
      throw new BadRequestException(ErrorEnum.INVALID_CODE);
    }

    await this.userService.updateUserPhone(uid, mobileInfo.phoneNumber);

    return mobileInfo.phoneNumber;
  }
}
